layui.use(["layer", "echarts"], function () {
  // 2020-03-25 HF sessionStorage中取出数据
  var token = sessionStorage.getItem("newtoken");
  //站点的名称
  var SaveStation = JSON.parse(sessionStorage.getItem("SaveStation"));
  // 设备的名称
  var Savedevice = JSON.parse(sessionStorage.getItem("Savedevice"));

  //  给曲线具体位置名称 xx/xx/xx/某某折线图
  // var SaveCurveName = JSON.parse(sessionStorage.getItem("SaveCurveName"));
  //  接口上传需要的数据
  // var HcurveName = sessionStorage.getItem("SaveName");

  var PicRequest = JSON.parse(sessionStorage.getItem("PicRequest"));

  var $ = layui.jquery,
    echarts = layui.echarts;
  $("#Myloading2").remove();
  /*************曲线图初始化*******************/
  var beginTime1 = $("#beginTime").val();
  var endTime1 = $("#endTime").val();

  if (beginTime1 == "" && endTime1 == "") {
    function add0(m) {
      return m < 10 ? "0" + m : m;
    } //避免少0
    // 当前时间
    var time = new Date();
    var year = time.getFullYear();
    var month = time.getMonth() + 1;
    var date = time.getDate();
    var hours = time.getHours();
    var minutes = time.getMinutes();
    var seconds = time.getSeconds();
    var s2 =
      year +
      "-" +
      add0(month) +
      "-" +
      add0(date) +
      " " +
      add0(hours) +
      ":" +
      add0(minutes) +
      ":" +
      add0(seconds);
    var yesterday = new Date(time - 3000 * 60 * 60 * 24);
    var y = yesterday.getFullYear();
    var m = yesterday.getMonth() + 1;
    var d = yesterday.getDate();
    var s1 =
      y +
      "-" +
      add0(m) +
      "-" +
      add0(d) +
      " " +
      add0(0) +
      ":" +
      add0(0) +
      ":" +
      add0(0);
    // console.log(s1);
    $("#beginTime").val(s1);
    $("#endTime").val(s2);

    // 实时更新当前时间
    var cltime = setInterval(function () {
      let nowtime = new Date();
      var s1 = GMTToStr(nowtime);
      $("#endTime").val(s1);
    }, 1000);

    // 初始化为当前一天的时间
    function getArresterTime() {
      var beginTime1 = $("#beginTime").val();
      var endTime1 = $("#endTime").val();
      $.ajax({
        url:
          "/oms-web/map/arrester/time-list?token=" +
          token +
          "&terminalNo=" +
          PicRequest.termNumber +
          "&beginTime=" +
          beginTime1 +
          "&endTime=" +
          endTime1,
        dataType: "json",
        type: "GET",
        contentType: "application/json",
        success: function (data) {
          if (data.code === 0) {
            index = layer.load(1);
            layer.close(index);
            writeList(data);
          }
        },
        error: function () {
          layer.msg("数据请求错误,请检查时间格式！");
          layer.close(index);
        },
      });
    }
    console.log(getArresterTime());
  }
  // 左边时间列表
  function writeList(data) {
    var html_txt = "";
    $("#timeList").empty(html_txt);
    for (var i = 0; i < data.data.length; i++) {
      html_txt = "<li  style='margin:20px; '>" + data.data[i] + "</li>";
      // 填充文本
      $("#timeList").append(html_txt);
    }
    // 点击左侧时间，触发曲线
    var time = document.getElementById("timeList").getElementsByTagName("li");
    if (time.length == 0) {
      $("#empty").show();
      $("#ArrTable").hide();
    } else {
      $("#empty").hide();
      $("#ArrTable").show();
    }
    for (var i = 0; i < time.length; i++) {
      time[i].onclick = function () {
        // console.log(this.firstChild.nodeValue);
        var needTime = this.firstChild.nodeValue;
        getHcurveData(needTime);
      };
    }
  }

  // 获取时间 请求数据
  $("#CurveSeach").click(function () {
    var beginTime = $("#beginTime").val();
    var endTime = $("#endTime").val();
    // 判断时间非空
    if (beginTime != "" && endTime != "") {
      function getDaysByDateString(dateString1, dateString2) {
        var startDate = Date.parse(dateString1);
        var endDate = Date.parse(dateString2);
        var diffDate = endDate - startDate + 1 * 24 * 60 * 60 * 1000; //
        var days = parseInt(diffDate / (1 * 24 * 60 * 60 * 1000));
        return days;
      }
      // 验证查询时间   不能过大和过小
      days = getDaysByDateString(beginTime, endTime);
      if (days > 180) {
        layer.msg("错误！查询时间段不能大于180天");
        return false;
      }
      if (days < 0 || days == 0) {
        layer.msg("错误！开始时间必须小于结束时间");
        return false;
      }
      index = layer.load(1);
      // getHcurveData(beginTime, endTime);
      getArresterTime(beginTime, endTime);
    } else {
      layer.msg("请填写开始时间 -- 结束时间！");
    }
    // console.log(beginTime, endTime);
  });

  //2020-03-27 HF  请求曲线接口
  function getHcurveData(needTime) {
    $.ajax({
      url:
        "/oms-web/map/arrester?token=" +
        token +
        "&time=" +
        needTime +
        "&terminalNo=" +
        PicRequest.termNumber,
      dataType: "json",
      type: "get",
      contentType: "application/json",
      success: function (data) {
        if (data.code === 0) {
          // loading加载动画
          layer.close(index);
          if (data.data != null && data.data != undefined) {
            var l = [];
            var x;
            for (let key in data.data) {
              x = key;
              var m =
                SaveStation.text +
                ">" +
                Savedevice.text +
                ">" +
                PicRequest.text +
                ">" +
                "避雷器录波图";
            }
            // x 轴
            for (var i = 0; i < data.data[1].value.length; i++) {
              l.push(i);
            }

            var echartsPies = echarts.init(
              document.getElementById("echarts-pies"),
              "walden"
            );
            var option = {
              title: {
                text: m,
                textStyle: {
                  color: "#1aa094",
                  left: "80px",
                  fontSize: 14,
                },
              },
              tooltip: {
                trigger: "axis",
              },
              grid: {
                top: 45,
                left: "3%",
                right: "4%",
                bottom: "5%",
                containLabel: true,
              },
              toolbox: {
                right: "20px",
                feature: {
                  dataView: {
                    show: true,
                    title: "数据视图",
                    //readOnly: true, //设置只读，会隐藏刷新按钮。
                    lang: ["数据视图", "关闭", "导出Excel"],
                    contentToOption: function (opts) {
                      var filename = JSON.parse(
                        sessionStorage.getItem("SaveAlarmName")
                      );
                      // console.log(filename);

                      $("#tableExcel_Day").table2excel({
                        exclude: ".noExl", //过滤位置的 css 类名
                        filename: filename[0].text + "走势图" + ".xls", //文件名称
                        name: "Excel Document Name.xls",
                        exclude_img: true,
                        exclude_links: true,
                        exclude_inputs: true,
                      });
                    },
                    optionToContent: function (opt) {
                      var axisData = opt.xAxis[0].data; //坐标数据
                      var series = opt.series; //折线图数据
                      var tdHeads =
                        '<td  style="padding: 5px 10px">时间-序号</td>'; //表头第一列
                      var tdBodys = ""; //表数据
                      //组装表头
                      // for (var i = 0; i < series.length; i++) {
                      tdHeads += '<td style="padding: 5px 10px">数值</td>';
                      // }
                      var table =
                        '<table value="' +
                        series[0].name +
                        '" id="tableExcel_Day" border="1" style="width:100%;text-align:center" ><tbody><tr style="background:coral;">' +
                        tdHeads +
                        " </tr>";
                      //组装表数据
                      for (var i = 0, l = axisData.length; i < l; i++) {
                        for (var j = 0; j < series.length; j++) {
                          var temp = series[j].data[i];
                          if (temp != null && temp != undefined) {
                            tdBodys += "<td>" + parseFloat(temp) + "</td>";
                          } else {
                            tdBodys += "<td></td>";
                          }
                        }
                        table +=
                          '<tr class="myColor"><td style="padding: 5px 10px">' +
                          axisData[i] +
                          "</td>" +
                          tdBodys +
                          "</tr>";
                        tdBodys = "";
                      }
                      table += "</tbody></table>";
                      return table;
                    },
                  },
                  saveAsImage: { backgroundColor: "#fff" },
                },
              },
              xAxis: [
                {
                  type: "category",
                  boundaryGap: false,
                  data: l,
                  axisLabel: {
                    fontSize: 13, //字体大小
                    interval: "auto",
                    showMaxLabel: true,
                    // rotate: 45,
                  },
                  // axisLine: {
                  //   lineStyle: {
                  //     color: "#1aa094",
                  //     // width: 2, //这里是为了突出显示加上的
                  //   },
                  // },
                },
              ],
              dataZoom: [
                // {
                //   type: "slider",
                //   realtime: true,
                //   bottom: -2,
                //   start: 0,
                //   end: 100,
                // },
                {
                  type: "inside",
                  realtime: true,
                  start: 0,
                  end: 500,
                },
              ],
              yAxis: [
                {
                  type: "value",
                  axisLabel: {
                    formatter: function (res) {
                      // // 判断给单位
                      // if (JSON.parse(HcurveName)[0].unitOfMeasurement != null) {
                      //   //    增加中括号
                      //   return ` ${[
                      //     res + JSON.parse(HcurveName)[0].unitOfMeasurement,
                      //   ]}`;
                      // } else {
                      //   return `${res} `;
                      // }
                      return `${res} %`;
                    },
                  },
                  axisLine: {
                    lineStyle: {
                      symbol: "arrow",
                      color: "#1aa094",
                      width: 2, //这里是为了突出显示加上的
                    },
                  },
                },
              ],
              series: [],
            };
            console.log(data.data);

            data.data.map((item) => {
              const seriesItem = {
                name: item.keyName,
                type: "line",
                showSymbol: false, //悬停才显示圆圈
                //    stack: '总量',
                data: item.value,
                smooth: true,
                // symbol: "circle", //实心圆圈
                markPoint: {
                  // 地图样式的特效显示
                  data: [
                    { type: "max", name: "最大值" },
                    { type: "min", name: "最小值" },
                  ],
                },
              };

              option.series.push(seriesItem);
              // console.log(option);
            });
            echartsPies.setOption(option);
          }
        }
      },
      error: function () {
        layer.msg("数据请求错误,请检查时间格式！");
        layer.close(index);
      },
    });
  }

  //获取时间函数
  function GMTToStr(time) {
    function add0(m) {
      return m < 10 ? "0" + m : m;
    } //避免少0
    var time = new Date(time);
    var year = time.getFullYear();
    var month = time.getMonth() + 1;
    var date = time.getDate();
    var hours = time.getHours();
    var minutes = time.getMinutes();
    var seconds = time.getSeconds();
    return (
      year +
      "-" +
      add0(month) +
      "-" +
      add0(date) +
      " " +
      add0(hours) +
      ":" +
      add0(minutes) +
      ":" +
      add0(seconds)
    );
  }

  $("#beginTime").datetimepicker({
    language: "zh-CN", //显示中文
    format: "yyyy-mm-dd hh:ii:ss", //显示格式
    // minView: "month",//设置只显示到月份
    initialDate: new Date(), //初始化当前日期
    autoclose: true, //选中自动关闭
    todayBtn: true, //显示今日按钮
    language: "zh-CN",
  });
  $("#endTime")
    .datetimepicker({
      language: "zh-CN", //显示中文
      format: "yyyy-mm-dd hh:ii:ss", //显示格式
      // minView: "month",//设置只显示到月份
      initialDate: new Date(), //初始化当前日期
      autoclose: true, //选中自动关闭
      todayBtn: true, //显示今日按钮
      // minView:'month',
      language: "zh-CN",
    })
    .on("changeDate", function (ev) {
      window.clearInterval(cltime);
    });
});
